

<template>
    <tm-app class="phoneLogin" bgImg="white">
        <!-- <image
            class="psa"
            style="width:750rpx;height:834rpx;top:0;left:0;right:0;z-index:1;"
            src="../../static/bg1.jpg"
            mode=""
        ></image> -->
        <view :style="{height:systemInfo.statusBarHeight + 'px'}"></view>
        <tm-navbar style="postion:relative;z-index:10;" :height="50" :margin="[0,0]" :padding="[0,0]" :fontSize="32" title="手机号登录" :transprent="true">
		</tm-navbar>
        <view class="content psr">
            <!-- <view class="title_main">手机号登录</view> -->
            <view class="inps">
                <view class="inp_box d-flex a-center" :class="{focus:inp1Focus}">
                    <view class="pre d-flex a-center j-center">
                        <view class="txt d-flex a-center j-center">+86</view>
                        <view style="height:40rpx;border-right:1px solid#ccc;"></view>
                    </view>
                    <input @focus="inp1Focus=true" @blur="inp1Blur" maxlength="11" type="number" class="inp"  v-model="phoneNum" placeholder="请输入11位手机号"/>
                </view>

                <view v-show="loginType==='password' || loginType==='codeAndPassword'" class="inp_box d-flex a-center" style="margin-top:20rpx;" :class="{focus:inp3Focus}">
                    <view class="pre d-flex a-center j-center">
                        <view class="txt d-flex a-center j-center">
                            <i class="tmicon tmicon-lock" style="font-size:30rpx;"></i>
                        </view>
                        <view style="height:40rpx;border-right:1px solid#ccc;"></view>
                    </view>
                    <input @focus="inp3Focus=true" @blur="inp3Blur" minlength="8" maxlength="16" :type="inpType" class="inp" style="width:370rpx;"  v-model="password" placeholder="请输入密码"/>
                    <view class="btn btn1 d-flex a-center j-center" @tap="triggleType">
                        <i class="tmicon tmicon-eye-fill" v-show="inpType==='password'"></i>
                        <i class="tmicon tmicon-eyeslash-fill" v-show="inpType==='text'"></i>
                    </view>
                </view>
				
				<view v-show="loginType==='code' || loginType==='codeAndPassword'" class="inp_box d-flex a-center" style="margin-top:20rpx;" :class="{focus:inp2Focus}">
				    <view class="pre d-flex a-center j-center">
				        <view class="txt d-flex a-center j-center">
				            <i class="tmicon tmicon-key" style="font-size:30rpx;"></i>
				        </view>
				        <view style="height:40rpx;border-right:1px solid#ccc;"></view>
				    </view>
				    <input @focus="inp2Focus=true" @blur="inp2Blur" maxlength="6" type="number" class="inp" style="width:280rpx;" v-model="vailCode" placeholder="请输入验证码"/>
				    <view v-show="showGetCode" class="btn d-flex a-center j-center" @tap="getCode">
				        <text class="text1">获取验证码</text>
				    </view>
				    <view v-show="!showGetCode" class="btn seconds d-flex a-center j-center">{{ seconds }}</view>
				</view>
            </view>

            <view v-if="!loading" class="btn_main d-flex a-center j-center" @tap="login">登录</view>
			<view v-else class="btn_main_no d-flex a-center j-center">登录中...</view>

            <view v-show="loginType==='code'" class="pasawordLogin d-flex a-center j-center c_main" @tap="loginType='password'">
                密码登录
            </view>


            <view v-show="loginType==='password'" class="pasawordLogin1 d-flex a-center j-between">
                <text class="uline"  @tap="loginType='code'">验证码登录</text>
                <text class="uline" @tap="goForget">忘记密码?</text>
            </view>


            <view class="bottom_box d-flex d-c a-center">
                <view v-if="!VER.ver"  class="wxLogin" @tap="wxlogin">
                    <view class="wxLogo d-flex a-center j-center">
                        <tm-icon  :font-size="80" color="#fff" name="icon-weixin"></tm-icon>
                    </view>
                    <view class="c_main f28" style="margin-top:20rpx;">
                        微信登录
                    </view>
                </view>
                <tm-checkbox
                    class="check"
                    outlined
                    v-model="readed"
                    :size="28"
                    :font-size="22"
                    color="#23e2a6"
                    :value="true"
                    label=""
                    @change="handleCheck"
                >
                    <view class="read">
                        我已阅读并同意<text class="uline" @tap="goUserAgreement">《用户协议》</text>、<text class="uline" @tap="goPrivacyPolicy">《隐私协议》</text>
                    </view>
                
                </tm-checkbox>
            </view>
        </view>
        <agree ref="agree_ref" @agree="handleAgree"></agree>
            <!-- 
            <tm-checkbox class="check" outlined v-model="readed" @change="ccc" color="green" :value="true" label="我已阅读并同意《用户协议》、《隐私协议》"></tm-checkbox> -->
    </tm-app>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { onReady, onShow,onLoad } from "@dcloudio/uni-app";
import { wxAuth,getUserDetail,getVerCode,codeLogin,pwdLogin } from "@/api/api";
import md5 from 'js-md5';
import { userData as userDataStore }  from '@/store/userData'
import { imLogin } from '@/hooks/imLogin'
import CryptoJS from 'crypto-js'
import { systemInfo as  systemInfoStore}  from '@/store/systemInfo'
import agree from "@/components/agree.vue";
import { config as configStore } from "@/store/config";
import { ver } from "@/store/ver";
const VER = ver();
const config: any = configStore();
const handleCheck = (bool:Boolean) => {
    config.setConfig({agreement:bool});

};

const userData:any = userDataStore();
const msg:any = ref(null);
const readed = ref(false);
const loginType = ref('code');
const systemInfo:any = systemInfoStore();
const inp1Focus = ref(false);
const inp2Focus = ref(false);
const inp3Focus = ref(false);
const phoneNum = ref("");
const vailCode = ref(null);
const phoneError = ref(false);
const seconds = ref(60);
const showGetCode = ref(true);
const inpType = ref('password');
const password = ref("");

const agree_ref = ref(null);
const handleAgree = ()=>{
    readed.value = true;
}
const loading = ref(false)//是否加载中

const goUserAgreement = ()=>{
    uni.navigateTo({
		url:`/pages/webview/webview?title=用户协议&url=http://52pp365.com/yonghuxieyi.html`
	});
}

const goPrivacyPolicy = ()=>{
    uni.navigateTo({
		url:`/pages/webview/webview?title=隐私政策&url=http://52pp365.com/yinsizhengce.html`
	});
}



const inp1Blur = ()=>{
    inp1Focus.value=false;
    const bool = uni.$tm.u.isPhone(phoneNum.value);
    phoneError.value = !bool;
}

const inp2Blur = ()=>{
    inp2Focus.value=false;
}

const inp3Blur = ()=>{
    inp3Focus.value=false;
}
const triggleType = ()=>{
    inpType.value = inpType.value === 'password'?'text':'password';
}



const getCode = async ()=>{
    seconds.value = 60;
    showGetCode.value = true;
    const bool = uni.$tm.u.isPhone(phoneNum.value);
    if(!bool){
        uni.showToast({
            icon: "none",
            title: '您输入的手机号有误，请检查',
            duration: 1500,
        });
        return
    }

    const res:any = await getVerCode({phone:phoneNum.value,messageType:'1'});
    const { flag } = res;
    if(flag===1){
        uni.showToast({
            icon: "none",
            title: '验证码已成功发送',
            duration: 1500,
        });
        showGetCode.value = false;
        let int = setInterval(()=>{

            if(seconds.value===1){
                showGetCode.value = true;
                clearInterval(int);
                return
            }

            seconds.value = seconds.value-1
        },1000)
    }
    
}


const goWxlogin = () => {
    uni.redirectTo({
            url: '/pages/login/login',
            animationType: 'fade-in',
    });
}

const goForget = () => {
    console.log('goForget')
    uni.navigateTo({
        url: '/pages/forgetPwd/forgetPwd',
    });
}


const login = ()=>{
	
    if(loginType.value==='code'){
        loginByCode();
    }else{
        console.log('loginByPwd')
        loginByPwd();
    }
}

const loginByCode = async ()=>{

    if(!readed.value){
        const bool = await agree_ref.value.open1();
        if(!bool){
            return;
        }
    }


    const bool = uni.$tm.u.isPhone(phoneNum.value);

    if(!bool){
        uni.showToast({
            icon: "none",
            title: '您输入的手机号有误，请检查',
            duration: 1500,
        });
        return
    }
    if(!vailCode.value){
        uni.showToast({
            icon: "none",
            title: '请输入正确的验证码',
            duration: 1500,
        });
        return
    }
	
    const params = {
        phone:phoneNum.value,
        authCode:md5(vailCode.value)
    }
	loading.value = true;
    const res:any = await codeLogin(params)
    const {flag,data,message} = res;
    console.log(res);
    if(flag!==1){
		loading.value = false;
        uni.showToast({
            icon: "none",
            title: message||'登录失败,请稍后再试',
            duration: 1500,
        });
        return
    }
    const {id,nickName,token,device} = data;
	uni.setStorageSync(phoneNum.value,device)//保存手机号对应的设备码
    uni.setStorageSync('api_token',token)
    userData.setUserData({id,nickName})
    await GetUserData(id);
    uni.showToast({
            icon: "none",
            title:'登录成功',
            duration: 1500,
        });
    imLogin(id);
}
const loginByPwd = async ()=>{
     if(!readed.value){
        const bool = await agree_ref.value.open1();
        if(!bool){
            return;
        }
        return
    }

    const bool = uni.$tm.u.isPhone(phoneNum.value);
    if(!bool){
        uni.showToast({
            icon: "none",
            title:'您输入的手机号有误，请检查',
            duration: 1500,
        });
        return
    }

    if(!password.value){
        uni.showToast({
            icon: "none",
            title:'请输入密码',
            duration: 1500,
        });
        return
    }
	if(loginType.value =='codeAndPassword'){
		if(!vailCode.value){
		    uni.showToast({
		        icon: "none",
		        title: '请输入正确的验证码',
		        duration: 1500,
		    });
		    return
		}
	}
    const keyStr = '6538e688e4e97b56';

    const pwd = CryptoJS.AES.encrypt(password.value, CryptoJS.enc.Utf8.parse(keyStr), {
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7
        }).toString()



    var key = CryptoJS.enc.Utf8.parse("keyStr");
	const deviceValue = uni.getStorageSync(phoneNum.value);
    const params:any = {
        phone:phoneNum.value,
        password:pwd,
		device:deviceValue
    }
	if(loginType.value =='codeAndPassword'){
		params.authCode = md5(vailCode.value)
	}
	loading.value = true;
    const res:any = await pwdLogin(params);
    console.log(res)
    
    const {flag,data,message} = res;
	
	if(flag==1169){
		loading.value = false;
		loginType.value ='codeAndPassword';
		uni.showToast({
		    icon: "none",
		    title:'非常用设备，请发送短信验证',
		    duration: 1500,
		});
		return
	}
    if(flag!==1){
		loading.value = false;
        uni.showToast({
            icon: "none",
            title:message||'登录失败,请稍后再试',
            duration: 1500,
        });
        return
    }

    const {id,nickName,token,device} = data;
	uni.setStorageSync(phoneNum.value,device)//保存手机号对应的设备码
    uni.setStorageSync('api_token',token)
    userData.setUserData({id,nickName})
    await GetUserData(id);
    uni.showToast({
		icon: "none",
		title:'登录成功',
		duration: 1500,
	});
    imLogin(id);
}

const  GetUserData = async (id1:string) => {
    const detail:any = await getUserDetail({id:id1});
    const {flag,data} = detail;
    console.log(detail);
    if(flag!==1){
        setTimeout(()=>{
            uni.navigateTo({
                url: '/pages/login/login',
                animationType: 'fade-in',
            });
        },2000)
    }
    uni.setStorageSync('USER_DATA',data);
    userData.setUserData(data)
    return true;
}

const wxlogin = () => {

    if(!readed.value){
        uni.showToast({
            icon: "none",
            title:'请先勾选并同意《用户协议》和《隐私协议》',
            duration: 1500,
        });
        return
    }

    uni.login({
        provider: "weixin",
        onlyAuthorize: true, 
        async success(event) {
            // uni.showToast({
            //     icon: "error",
            //     title: "登录失败,请稍后重试!",
            //     duration: 100000,
            // });
        


            const res: any = await wxAuth({ code: event.code });
            const { flag, data } = res;
            if (flag !== 1) {
                uni.showToast({
                    icon: "none",
                    title:'登录出错，请稍后再试！',
                    duration: 1500,
                });
                return
            }

            const {id,token,device} = data;
			uni.setStorageSync(phoneNum.value,device)//保存手机号对应的设备码
            uni.setStorageSync('api_token',token)
            const bool = await GetUserData(id);
            if(bool){
                imLogin(userData.id);
            }
        },
        fail: function (err) {
            console.log(err);
        },
    });
};



onReady(() => {
    uni.getSystemInfo({
        success(result) {
            systemInfo.setSystemInfo(result);
        },
    });
});

onLoad((option:any) => {
    if(option.loginType){
        loginType.value = option.loginType;
    }
});

onShow(() => {
    readed.value = config.agreement;
});
</script>

<style lang="scss" scoped>
@import './phoneLogin.scss';
</style>

